package juc.piped;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/*管道*/
public class Piped {
    public static void main(String[] args) throws IOException {
        PipedReader reader = new PipedReader();
        PipedWriter writer = new PipedWriter();
        Producer producer = new Producer(writer);
        Consumer consumer = new Consumer(reader);
        writer.connect(reader);
        new Thread(producer).start();
        new Thread(consumer).start();
    }


}

class Producer implements Runnable {

    private PipedWriter writer;

    public Producer(PipedWriter writer) {
        this.writer = writer;
    }

    @Override
    public void run() {
        try {
            writer.write("from Producer");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

class Consumer implements Runnable {
    private PipedReader reader;

    public Consumer(PipedReader reader) {
        this.reader = reader;
    }

    @Override
    public void run() {

        try {
            char[] cbuf = new char[20];
            reader.read(cbuf, 0, cbuf.length);
            System.out.println("管道流中的数据为: " + new String(cbuf));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}